package cn.b.sky.mes.qm.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.b.sky.mes.qm.model.DefectAttribute;
import cn.b.sky.mes.qm.model.DefectAttributeEnum;
import cn.b.sky.mes.qm.model.condition.DefectAttributeCondition;
import cn.b.sky.mes.qm.service.DefectAttributeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.common.enums.DwzCallbackType;
import cn.b.sky.common.enums.DwzStatusCode;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;
import cn.b.sky.mes.qm.enums.DefectAttributeValueType;

import com.alibaba.fastjson.JSON;

/**
 * <strong>Title : DefectAttributeController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.pp.controller<br></strong>
 * <strong>Description : </strong>缺陷属性控制器<br> 
 * <strong>Create on : 2015年12月9日 上午10:58:28<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping("/defectAttribute/*")
public class DefectAttributeController extends SecurityController {
  
  private static final String ECODE = "ECode";  
  
  private static final String PATTERN = "pattern";
  
  @Resource
  DefectAttributeService defectAttributeService;

  @Resource
  ECodeService eCodeService;

  @RequestMapping("defectAttribute_list")
  public String selectDefectAttributeListByCondition(@ModelAttribute("condition") DefectAttributeCondition condition,
      String navTabId, Model model){
    condition.setSiteCode(getSiteCode());
    List<DefectAttribute> list = defectAttributeService.selectDefectAttributeListByCondition(condition);
    int count = defectAttributeService.selectDefectAttributeCountByCondition(condition);

    condition.setTotalCount(count);
    condition.setData(list);

    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.QM_DEFECTATTRIBUTEVALUETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute(ECODE, ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("page", condition);
    return "qm/defectAttribute/defectAttribute_list";
  }

  @RequestMapping("addDefectAttribute")
  public String addDefectAttribute(String navTabId, Model model) {
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute(PATTERN, "add");
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.QM_DEFECTATTRIBUTEVALUETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute(ECODE, ecode);
    return "qm/defectAttribute/defectAttribute_add";
  }

  @RequestMapping("modifyDefectAttribute")
  public String modifyDefectAttribute(String id, String navTabId, Model model) {
    DefectAttribute attribute = defectAttributeService.getDefectAttribute(getSiteCode(), id);
    if (attribute.getValueTypeECode().equals(DefectAttributeValueType.ENUM.getValue())) {
      attribute.getAttributeEnum().addAll(
          defectAttributeService.selectDefectAttributeEnumList(attribute.getSiteCode(), attribute.getAttributeCode()));
    }
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.QM_DEFECTATTRIBUTEVALUETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    model.addAttribute(ECODE, ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("defectAttribute", attribute);
    model.addAttribute(PATTERN, "modify");

    return "qm/defectAttribute/defectAttribute_add";
  }

  @RequestMapping("viewDefectAttribute")
  public String viewDefectAttribute(String id, String navTabId, Model model) {
    DefectAttribute attribute = defectAttributeService.getDefectAttribute(getSiteCode(), id);
    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.QM_DEFECTATTRIBUTEVALUETYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    String view = "qm/defectAttribute/defectAttribute_view";
    if (DefectAttributeValueType.ENUM.getValue().equals(attribute.getValueTypeECode())) {
      attribute.getAttributeEnum().addAll(
          defectAttributeService.selectDefectAttributeEnumList(attribute.getSiteCode(), attribute.getAttributeCode()));
      view = "qm/defectAttribute/defectAttribute_EnumView";
    }
    model.addAttribute(ECODE, ecode);
    model.addAttribute(NAVTABID, navTabId);
    model.addAttribute("defectAttribute", attribute);
    model.addAttribute(PATTERN, "view");

    return view;
  }

  @RequestMapping("saveDefectAttribute")
  @ResponseBody
  public DWZResult saveDefectAttribute(String id, DefectAttribute attribute, String navTabId, Model model,
      String[] attributeValue) {
    if (attribute == null || StringUtils.isBlank(attribute.getAttributeCode())) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }

    if (DefectAttributeValueType.ENUM.getValue().equals(attribute.getValueTypeECode()) && attributeValue != null) {
      for (String value : attributeValue) {
        DefectAttributeEnum attributeEnum = new DefectAttributeEnum(getSiteCode(), attribute.getAttributeCode(), value);
        setCreateInfo(attributeEnum);
        attribute.getAttributeEnum().add(attributeEnum);
      }
    }
    attribute.setSiteCode(getSiteCode());
    setCreateInfo(attribute);
    if (attribute.getLockFlag() == null) {
      attribute.setLockFlag(0);
    }
    if (attribute.getRequiredFlag() == null) {
      attribute.setRequiredFlag(0);
    }
    if (StringUtils.isBlank(id)) {
      defectAttributeService.insertDefectAttribute(attribute);
    } else {
      defectAttributeService.updateDefectAttribute(attribute);
    }
    return dialogAjaxDone(
        getImeViewMessageI18n(null, "successfulOperation.M"),
        null, null, null, null);
  }

  @RequestMapping("deleteDefectAttribute")
  @ResponseBody
  public DWZResult deleteDefectAttribute(String navTabId, Model model, HttpServletRequest request) {
    String ids = request.getParameter("ids");
    if (StringUtils.isBlank(ids)) {
      return ajaxError(getImeViewMessageI18n(null,
          SystemConstant.PARAMETERNULL));
    }

    String[] idArr = ids.split(",");
    BatchJobReport[] reports = new BatchJobReport[idArr.length];
    int failures = 0;
    for (int i = 0; i < idArr.length; i++) {
      reports[i] = defectAttributeService.deleteDefectAttribute(getSiteCode(), idArr[i]);
      if (!reports[i].isSuccess()) {
        failures += 1;
      }
    }

    if (failures == 0) {
      return navTabAjaxDone(navTabId, null, null, null,
          getImeViewMessageI18n(null, "successfulOperation.M"),
          null);
    } else {
      return batchjobAjaxDone( request, Arrays.asList(reports));
    }
  }

  @RequestMapping("validateDefectAttributeCode")
  @ResponseBody
  public boolean validateDefectAttributeCode(String attributeCode) {
    if (StringUtils.isBlank(attributeCode)) {
      return true;
    } else {
      DefectAttribute level = defectAttributeService.getDefectAttribute(getSiteCode(), attributeCode);
      return level == null;
    }
  }

  @RequestMapping("changeDialogSize")
  @ResponseBody
  public DWZResult changeDialogSize(String defectAttributeCode, String navTabId, HttpServletRequest request) {
    if (StringUtils.isBlank(defectAttributeCode)) {
      return ajaxError(this.getImeViewMessageI18n(SecurityContextUtil.getLanguageCode(), SystemConstant.PARAMETERNULL));
    }

    DefectAttribute attribute = defectAttributeService.getDefectAttribute(getSiteCode(), defectAttributeCode);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("title",
        getImeViewMessageI18n(null, "viewDefectAttribute.D"));
    String forwardUrl = request.getContextPath() + "/manage/defectAttribute/viewDefectAttribute?id="
        + attribute.getAttributeCode();
    if (attribute.getValueTypeECode().equals(DefectAttributeValueType.ENUM.getValue())) {
      map.put("type", "enum");
    }
    String jsonData = JSON.toJSONString(map);
    return getDWZJsonObject(DwzStatusCode.OK, null, navTabId, "viewDefectAttribute", DwzCallbackType.EMPTY, forwardUrl,
        null, jsonData);
  }

}